package site.xuqing.socketbus.core.handler;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;

import site.xuqing.nobean.NoBean;
import site.xuqing.nobean.obj.NonObject;
import site.xuqing.socketbus.listener.OnMsgReceive;

/**
 * @author xuqing
 * @Description 客户端接收消息线程
 * @createTime 2022年01月21日 14:37:52
 */
public class ClientReceiveHandler extends Thread {
    private final Socket socket;
    private final OnMsgReceive mOnMsgReceive;
    
    public ClientReceiveHandler(Socket socket, OnMsgReceive onMsgReceive) {
        this.socket = socket;
        this.mOnMsgReceive = onMsgReceive;
    }
    
    @Override
    public void run() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            while ((msg = bufferedReader.readLine()) != null) {
                System.out.println("##客户端：" + msg);
                if (mOnMsgReceive != null) {
                    NonObject nonObject = NoBean.formJson(msg);
                    mOnMsgReceive.onMsg(nonObject.getObject("data"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接异常断开");
        }
    }
}
